#!/bin/bash

# --- 实验配置 ---
set -e

TEST_FILE="./test_data.dat"
FILE_SIZE_GB=5 # 5 GB
STRIDE_KB=1024
DEVICE=$(lsblk -ndo pkname "$(findmnt -n -o source --target .)")

# --- 函数 ---
clear_caches() {
    echo "---"
    echo "Syncing filesystem and clearing system page cache..."
    sync
    sudo sh -c 'echo 3 > /proc/sys/vm/drop_caches'
    sleep 2
}

# =================================================================
# --- 脚本主逻辑 ---
# =================================================================

echo "=================================================="
echo " eBPF Adaptive Prefetching Experiment Runner"
echo "=================================================="
echo "Test File: ${TEST_FILE}"
echo "File Size: ${FILE_SIZE_GB} GB"
echo "Access Stride: ${STRIDE_KB} KB"
echo "Target Device for readahead: /dev/${DEVICE}"
echo "--------------------------------------------------"

# 步骤 1: 编译和准备
echo ">>> Step 1: Compiling all components..."



# --- 关键修改：指定 benchmark 的源码和输出路径 ---
echo "Building benchmark program..."
g++ -std=c++17 -O2 ./benchmark/benchmark.cpp -o ./benchmark/benchmark

echo "Checking for test file..."
# --- 关键修改：运行 benchmark/benchmark ---
if [ ! -f "$TEST_FILE" ]; then
    echo "Test file not found. Creating it now (this may take a while)..."
    ./benchmark/benchmark $TEST_FILE $STRIDE_KB $FILE_SIZE_GB
else
    echo "Test file already exists."
fi
echo ">>> Preparation complete."
echo ""


# 步骤 2: 运行实验场景

# --- 场景 1: 无优化基线 (Baseline) ---
echo ">>> Running Scenario 1: Baseline (No Prefetching)"
clear_caches
ORIGINAL_RA_BYTES=$(sudo blockdev --getra /dev/${DEVICE})
ORIGINAL_RA_KB=$((ORIGINAL_RA_BYTES / 2))
echo "Original readahead was: ${ORIGINAL_RA_KB} KB. Disabling it now."
sudo blockdev --setra 0 /dev/${DEVICE}
# --- 关键修改：运行 benchmark/benchmark ---
(time sudo ./benchmark/benchmark $TEST_FILE $STRIDE_KB $FILE_SIZE_GB) 2>&1 | tee baseline_output.txt
sudo blockdev --setra $ORIGINAL_RA_BYTES /dev/${DEVICE}
echo "Readahead restored to ${ORIGINAL_RA_KB} KB."
echo ""


# --- 场景 2: 内核默认优化 (Kernel Default) ---
echo ">>> Running Scenario 2: Kernel Default Prefetching"
clear_caches
echo "Using default kernel readahead: ${ORIGINAL_RA_KB} KB."
# --- 关键修改：运行 benchmark/benchmark ---
(time sudo ./benchmark/benchmark $TEST_FILE $STRIDE_KB $FILE_SIZE_GB) 2>&1 | tee kernel_default_output.txt
echo ""


# --- 场景 3: 本项目 eBPF 自适应优化 (Our System) ---
echo ">>> Running Scenario 3: Our eBPF-based Adaptive Prefetching"
clear_caches
echo "Disabling kernel readahead to isolate our system's performance."
sudo blockdev --setra 0 /dev/${DEVICE}
echo "Starting eBPF agent in the background (log: agent.log)..."
./agent > agent.log 2>&1 &
AGENT_PID=$!
sleep 3
echo "Agent started with PID ${AGENT_PID}. Running benchmark..."
# --- 关键修改：运行 benchmark/benchmark ---
(time sudo ./benchmark/benchmark $TEST_FILE $STRIDE_KB $FILE_SIZE_GB) 2>&1 | tee our_system_output.txt
echo "Benchmark finished. Stopping eBPF agent..."
if ps -p $AGENT_PID > /dev/null; then
   kill $AGENT_PID
   wait $AGENT_PID 2>/dev/null || true
   echo "Agent stopped."
else
   echo "Agent process was not running. Check agent.log for errors."
fi
sudo blockdev --setra $ORIGINAL_RA_BYTES /dev/${DEVICE}
echo "Readahead restored to ${ORIGINAL_RA_KB} KB."
echo ""

# 步骤 3: 结果汇总
echo "=================================================="
echo " Experiment Results Summary"
echo "=================================================="
echo -e "Scenario\t\tTotal Time (s)"
echo "--------------------------------------------------"
TIME_BASE=$(grep real baseline_output.txt | awk '{print $2}' | sed 's/m/ /;s/s//' | awk '{print $1*60+$2}')
echo -e "1. Baseline\t\t${TIME_BASE}"
TIME_KERNEL=$(grep real kernel_default_output.txt | awk '{print $2}' | sed 's/m/ /;s/s//' | awk '{print $1*60+$2}')
echo -e "2. Kernel Default\t${TIME_KERNEL}"
TIME_OURS=$(grep real our_system_output.txt | awk '{print $2}' | sed 's/m/ /;s/s//' | awk '{print $1*60+$2}')
echo -e "3. Our System\t\t${TIME_OURS}"
echo "--------------------------------------------------"
echo "Check 'agent.log' for detailed eBPF agent activity."
echo "Experiment finished successfully!"